package web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.tapestry.json.JSONArray;
import org.apache.tapestry.json.JSONObject;
import org.springframework.util.CollectionUtils;

import util.MyGson;
import util.SpringContextHolder;

import com.opensymphony.xwork2.ActionSupport;

import constant.Constant;


/**
 * 
 * <b>基类 | Action</b><br>
 * 1.跳转列表页面<br>
 * 2.跳转新增页面<br>
 * 3.跳转编辑页面<br>
 * 4.跳转查看页面<br>
 * 5.获取当前登录用户<br>
 * 6.向界面输出内容<br>
 * 7.向界面写指定格式的JSON数据<br>
 * 8，向页面写入json数据，包括pojo验证失败的属性提示信息<br>
 * 9，验证权限<br>
 * 
 * GeBing 2012-11-8 下午2:08:18
 * 
 * @version 1.0.0
 * 
 */
public class BaseAction extends ActionSupport {

  private static final long serialVersionUID = 1L;
  protected static MyGson myGson = SpringContextHolder.getBean(MyGson.class);
  protected static final String JSON_ERROR_PAGE = "jsonErrorPage";

  public String jumpListPage() throws Exception {
    return SUCCESS;
  }

  /**
   * 
   * 向界面输出内容
   * 
   * @param data
   *        输出内容
   * @throws IOException
   *         void
   * @exception
   * @since 1.0.0
   */
  protected void printWriter(String data) throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    setBasicResponseHeader(response);
    response.setContentType("text/json;charset=utf-8");

    write(data, response);
  }

  /**
   * 访问页面失败时，在页面提示失败信息.
   * 
   * @param msg
   * @param jumpUrl
   * @throws IOException
   *         void
   * @exception
   * @since 1.0.0
   */
  protected void printMsgAndJump(String msg, String jumpUrl) throws IOException {

    HttpServletRequest req = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    setBasicResponseHeader(response);
    String contextName = req.getContextPath();

    response.setContentType("text/html;charset=utf-8");
    StringBuffer sb = new StringBuffer();
    sb.append("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"" + contextName
        + "/css/ifream.css\" />");
    sb.append("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"" + contextName
        + "/themes/redmond/jquery-ui-1.8.2.custom.css\" />");
    sb.append("<style>.window-coDiv{padding-top:24px;}</style>");
    sb.append("<script src=\"" + contextName + "/js/jquery-1.8.2.js\" type=\"text/javascript\"></script>");

    sb.append("<script src=\"" + contextName + "/js/jquery-ui-1.8.2.custom.min.js\" type=\"text/javascript\"></script>");
    sb.append("<script src=\"" + contextName + "/js/common/smsui.js\" type=\"text/javascript\"></script>");

    sb.append("<script type=\"text/javascript\">ctx=\"" + contextName + "\";$(function(){");
    // sb.append("var ctx = \"").append(contextName).append("\";");
    sb.append("SmsUI.Window.alertCallback(\"").append(msg).append("\",'提示信息',function(){");
    if (StringUtils.isNotBlank(jumpUrl)) {
      sb.append("parent.document.getElementById('rightIFrame').src = '" + contextName + jumpUrl + "';");
    }
    sb.append("},'y');});</script>");
    write(sb.toString(), response);
  }

  public void printMsgAndJump(String msg) throws IOException {
    HttpServletResponse response = ServletActionContext.getResponse();
    setBasicResponseHeader(response);
    response.setContentType("text/html;charset=utf-8");
    StringBuffer sb = new StringBuffer();
    sb.append("<script type=\"text/javascript\">");
    sb.append("alert(\"").append(msg).append("\",'提示信息'");
    sb.append("); history.back();");
    sb.append("</script>");
    write(sb.toString(), response);
  }

  private void setBasicResponseHeader(HttpServletResponse response) {
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
  }

  /**
   * 
   * 向界面输出内容
   * 
   * @param data
   *        输出内容
   * @param contentType
   *        返回的类型，默认为text/json;charset=utf-8
   * @throws IOException
   *         void
   * @exception
   * 
   * 
   * @since 1.0.0
   */
  protected void printWriter(String data, String contentType) throws IOException {
    if (contentType == null) {
      printWriter(data);
    } else {
      HttpServletResponse response = ServletActionContext.getResponse();
      setBasicResponseHeader(response);
      response.setContentType(contentType);

      write(data, response);
    }
  }

  private void write(String data, HttpServletResponse response) throws IOException {
    PrintWriter printWriter = response.getWriter();
    printWriter.write(data);
    printWriter.flush();
    printWriter.close();
  }

  /**
   * 写处理成功的查询参数为Id的JSON数据
   * 
   * @param message
   *        提示信息
   * @param createUrl
   *        新建路径
   * @param editUrl
   *        编辑路径
   * @param listUrl
   *        列表路径
   * @param id
   *        请求参数为id=id
   * @throws IOException
   * @exception
   * @since 1.0.0
   */
  protected void writerSuccessJSONDataById(String message, String createUrl, String editUrl, String listUrl, Long id)
      throws IOException {
    Map<String, Object> params = new HashMap<String, Object>();
    if (id != null)
      params.put("id", id);
    writerSuccessJSONData(message, createUrl, editUrl, listUrl, params);
  }

  /**
   * 写处理成功的JSON数据
   * 
   * @param message
   *        提示信息
   * @param createUrl
   *        新建路径
   * @param editUrl
   *        编辑路径
   * @param listUrl
   *        列表路径
   * @param params
   *        请求参数
   * @throws IOException
   * @exception
   * @since 1.0.0
   */
  protected void writerSuccessJSONData(String message, String createUrl, String editUrl, String listUrl,
      Map<String, Object> params) throws IOException {
    JSONObject json = new JSONObject();
    json.put("result", SUCCESS);
    json.put("message", message);
    String contextPaht = ServletActionContext.getRequest().getContextPath();
    if (StringUtils.isNotBlank(createUrl)) {
      json.put("createUrl", contextPaht + createUrl);
    }
    if (StringUtils.isNotBlank(editUrl)) {
      json.put("editUrl", contextPaht + editUrl);
    }
    if (StringUtils.isNotBlank(listUrl)) {
      json.put("listUrl", contextPaht + listUrl);
    }
    if (CollectionUtils.isEmpty(params) == false) {
      JSONArray param = new JSONArray();
      for (Map.Entry<String, Object> entry : params.entrySet()) {
        param.put(entry.getKey() + "=" + entry.getValue());
      }
      json.put("param", param);
    }
    printWriter(json.toString(), "text/html;charset=utf-8");
  }

  /**
   * 写处理失败的JSON数据
   * 
   * @param message
   *        提示信息
   * @throws IOException
   * @exception
   * @since 1.0.0
   */
  protected void writerErrorJSONData(String message) throws IOException {
    JSONObject json = new JSONObject();
    json.put("result", ERROR);
    json.put("message", message);
    printWriter(json.toString(), "text/html;charset=utf-8");
  }

  /**
   * 
   * 向界面写指定格式的JSON数据<br>
   * 格式为：{"result":"","message":"","url":""}
   * 
   * @param result
   *        执行结果，可选{success,failure}
   * @param message
   *        提示消息或错误信息
   * @param actionUrl
   *        action请求路径(执行成功后跳转的Action)，如：/sys/user/jumpListPage
   * @throws IOException
   *         void
   * @exception
   * @since 1.0.0
   */
  protected void writerJSONData(String result, String message, String actionUrl) throws IOException {
    JSONObject json = new JSONObject();
    putBasicInfo(result, message, actionUrl, json);
    printWriter(json.toString());
  }

  protected void writerJSONDataWithFile(String result, String message, String actionUrl) throws IOException {
    JSONObject json = new JSONObject();
    putBasicInfo(result, message, actionUrl, json);
    printWriter(json.toString(), "text/html;charset=utf-8");
  }

  /** 重载原来的writerJSONDataWithFile方法，增加了一个Map参数，可以动态扩展返回到前端的json数据内容 */
  protected void writerJSONDataWithFile(String result, String message, String actionUrl, Map<String, Object> params)
      throws IOException {
    JSONObject json = new JSONObject();
    putBasicInfo(result, message, actionUrl, json, params);
    printWriter(json.toString(), "text/html;charset=utf-8");
  }

  /** 重载原来的putBasicInfo方法，增加了一个Map参数，可以动态扩展返回到前端的json数据内容 */
  private void putBasicInfo(String result, String message, String actionUrl, JSONObject json, Map<String, Object> params) {
    if (!CollectionUtils.isEmpty(params)) {
      for (Map.Entry<String, Object> entry : params.entrySet()) {
        json.put(entry.getKey(), entry.getValue());
      }
    }
    json.put("result", result);
    json.put("message", message);
    json.put("url", ServletActionContext.getRequest().getContextPath() + actionUrl);
  }

  private void putBasicInfo(String result, String message, String actionUrl, JSONObject json) {
    json.put("result", result);
    json.put("message", message);
    json.put("url", ServletActionContext.getRequest().getContextPath() + actionUrl);
  }

  /**
   * 向页面写入json数据，包括pojo验证失败的属性提示信息
   * 
   * @param message
   * @param actionUrl
   * @param errorMapJson
   * @throws IOException
   *         void
   * @exception
   * @since 1.0.0
   */
  protected void writerJSONDataError(String message, String actionUrl, String errorMapJson) throws IOException {
    JSONObject json = new JSONObject();
    putBasicInfo(Constant.JsonResult.failure, message, actionUrl, json);
    json.put("errorMapJson", errorMapJson);
    printWriter(json.toString());
  }

  /** 编码下载文件名 */
  protected String encodeFileName() {
    String fileName = null;
    try {
      fileName = new String(getExportExcelName().getBytes("utf-8"), "ISO8859-1");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    return fileName;
  }

  /** 得到查询参数 */
  protected Map<String, Object> getParams() {
    return null;
  }

  /** 得到excel 标题列名 */
  protected String[] getTitle() {
    return null;
  }

  /** 得到导出excel的sheet name */
  protected String getSheetName() {
    return null;
  }

  /** 得到需要导出的PO的属性 */
  protected String[] getPoAttrs() {
    return null;
  }

  /** 导出的Excel的文件名称 */
  public String getExportExcelName() {
    return null;
  }

  /* 导出列表结束 */
  /**
   * 从参数中取得指定参数的值。
   * 
   * @throws UnsupportedEncodingException
   */
  public String getRequestParamter(String requestKey) throws UnsupportedEncodingException {
    HttpServletRequest request = ServletActionContext.getRequest();
    request.setCharacterEncoding(Constant.PROJECT_CODING);
    return request.getParameter(requestKey);
  }

  public HttpServletRequest getRequest() {
    HttpServletRequest request = ServletActionContext.getRequest();
    return request;
  }

  public HttpServletResponse getResponse() {
    return ServletActionContext.getResponse();
  }

}
